import { modelService } from '../services/model.js'
import logger from '../services/logger.js'

// 测试 Ollama 连接
export const testConnection = async (req, res) => {
  let { endpoint } = req.body
  
  try {
    // 解码 endpoint URL
    endpoint = decodeURIComponent(endpoint)
    
    // 确保 endpoint 是有效的 URL
    if (!endpoint.startsWith('http')) {
      endpoint = `http://${endpoint}`
    }
    
    // 移除可能的尾部斜杠
    endpoint = endpoint.replace(/\/$/, '')
    
    console.log('Testing connection to:', endpoint) // 添加日志
    
    // 尝试请求 Ollama API
    const response = await fetch(`${endpoint}/api/tags`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
      signal: AbortSignal.timeout(3000) // 使用更现代的超时方式
    })
    
    if (response.ok) {
      // 如果能获取到模型列表，说明连接正常
      const data = await response.json()
      res.json({
        success: true,
        message: 'Connection successful',
        data
      })
    } else {
      throw new Error(`Service responded with status: ${response.status}`)
    }
  } catch (error) {
    console.error('Ollama connection test failed:', error)
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to connect to Ollama service',
      error: {
        name: error.name,
        message: error.message,
        cause: error.cause?.message
      }
    })
  }
}

// 获取模型配置
export const getModelConfig = async (req, res) => {
  try {
    const config = modelService.getConfig()
    res.json(config)
  } catch (error) {
    logger.error('Failed to get model config:', error)
    res.status(500).json({
      success: false,
      message: error.message
    })
  }
}

// 更新模型配置
export const updateModelConfig = async (req, res) => {
  try {
    const newConfig = req.body
    const updatedConfig = await modelService.updateConfig(newConfig)
    res.json(updatedConfig)
  } catch (error) {
    logger.error('Failed to update model config:', error)
    res.status(500).json({
      success: false,
      message: error.message
    })
  }
}

// 获取模型列表
export const listModels = async (req, res) => {
  try {
    const models = await modelService.listModels()
    res.json(models)
  } catch (error) {
    logger.error('Failed to list models:', error)
    res.status(500).json({
      success: false,
      message: error.message
    })
  }
}

// 拉取模型
export const pullModel = async (req, res) => {
  try {
    const { name } = req.body
    const result = await modelService.pullModel(name)
    res.json(result)
  } catch (error) {
    logger.error('Failed to pull model:', error)
    res.status(500).json({
      success: false,
      message: error.message
    })
  }
}

// 获取模型状态
export const getModelStatus = async (req, res) => {
  try {
    const status = await modelService.getModelStatus()
    res.json(status)
  } catch (error) {
    logger.error('Failed to get model status:', error)
    res.status(500).json({
      connected: false,
      chat: { ready: false, loading: false },
      embedding: { ready: false, loading: false },
      error: error.message
    })
  }
} 